import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:xvideos/hj_model/video_model.dart';

import '../../../config/config.dart';
import '../../../hj_model/splash/ads_model.dart';
import '../../../routers/jump_router.dart';
import '../../../tools_base/global_store/store.dart';
import '../../../tools_base/widget/net_image_widget.dart';

class VideoAdWidget extends StatefulWidget {
  final List<AdsInfoModel>? adsInfos;
  final VideoModel? videoModel;
  final Function? finisiCallback;
  final Function? toVipCallback;
  final bool? showBackArrow;
  const VideoAdWidget({
    super.key,
    this.adsInfos,
    this.finisiCallback,
    this.videoModel,
    this.toVipCallback,
    this.showBackArrow = true,
  });

  @override
  State<StatefulWidget> createState() {
    return _VideoAdWidgetState();
  }
}

class _VideoAdWidgetState extends State<VideoAdWidget> {
  int countdownTime = 0;
  Timer? _timer;
  AdsInfoModel? adsModel;

  bool get isCanClose {
    bool isCanClose = false;
    if (globalStore.isVIP()) {
      isCanClose = true;
    } else if (widget.videoModel?.isCoinVideo() == true) {
      if (widget.videoModel?.vidStatus?.hasPaid == true) {
        isCanClose = true;
      }
    } else {}
    if (countdownTime <= 0 || _timer == null) {
      isCanClose = true;
    }
    return isCanClose;
  }

  @override
  void initState() {
    super.initState();
    int random = Random().nextInt(10);
    int index = random % (widget.adsInfos?.length ?? 1);
    adsModel = widget.adsInfos?[index];
    countdownTime = Config.adsTimeLongVideo;
    _timer = Timer.periodic(const Duration(seconds: 1), _timerCallback);
  }

  void _timerCallback(timer) {
    countdownTime--;
    if (countdownTime < 1) {
      countdownTime = -1;
      _timer?.cancel();
      _timer = null;
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.black,
      child: Stack(
        fit: StackFit.expand,
        children: [
          InkWell(
            onTap: () {
              pushToPageByLink(adsModel?.href, id: adsModel?.id);
            },
            child: NetworkImageLoader(
              imageUrl: adsModel?.cover ?? "",
              fit: BoxFit.fill,
            ),
          ),
          Positioned(
            top: 4,
            right: 4,
            child: GestureDetector(
              onTap: () {
                if (isCanClose) {
                  countdownTime = 0;
                  _timer?.cancel();
                  widget.finisiCallback?.call();
                } else {
                  widget.toVipCallback?.call();
                }
              },
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                decoration: const BoxDecoration(color: Color.fromRGBO(0, 0, 0, 0.5), borderRadius: BorderRadius.all(Radius.circular(20))),
                child: (countdownTime <= 0)
                    ? const Row(
                        children: [
                          Text(
                            '关闭',
                            style: TextStyle(color: Color(0xffff7f0f), fontSize: 12, fontWeight: FontWeight.w300),
                          ),
                        ],
                      )
                    : Row(
                        children: [
                          Text(
                            ' $countdownTime秒后',
                            style: const TextStyle(color: Colors.white, fontSize: 12, fontWeight: FontWeight.w300),
                          ),
                          Text(
                            isCanClose ? ' 关闭' : '关闭',
                            style: TextStyle(
                                color: isCanClose ? const Color(0xffff7f0f) : Colors.white, fontSize: 12, fontWeight: FontWeight.w300),
                          ),
                          if (globalStore.isVIP() == false && isCanClose == false)
                            const Text(
                              ' VIP跳过广告',
                              style: TextStyle(color: Color(0xffff7f0f), fontSize: 12, fontWeight: FontWeight.w300),
                            ),
                        ],
                      ),
              ),
            ),
          ),
          if (widget.showBackArrow == true)
            Align(
              alignment: Alignment.topLeft,
              child: GestureDetector(
                onTap: () {
                  Navigator.of(context).pop();
                },
                child: Container(
                  color: Colors.transparent,
                  width: 30,
                  height: 30,
                  margin: const EdgeInsets.only(top: 10, left: 10),
                  child: const Icon(
                    Icons.arrow_back_ios_sharp,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }
}
